/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package hibernate.connection_factory;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
import hibernate.entityes.*;
import java.util.Date;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.Session;

/**
 * Hibernate Utility class with a convenient method to get Session Factory
 * object.
 *
 * @author eleven
 */
public class HibernateUtil {

    public static long timer = 0;
    public static SessionFactory sessionFactory = null;

    public static void initConnectionFactory() {
        Date dt = new Date();
        timer = dt.getTime();
        try {
            sessionFactory = new AnnotationConfiguration()
                    .addAnnotatedClass(City.class)
                    .addAnnotatedClass(Distance.class)
                    .configure().buildSessionFactory();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    public static Session getOrInitSession() {
        try {
            Date curDate = new Date();
            long curTime = curDate.getTime();
            long tenminutes = 10 * 60 * 1000;
            if ((curTime - timer) > tenminutes) {
                destroy();
            } else {
                curDate = new Date();
                timer = curDate.getTime();
            }
            if (sessionFactory == null) {
                initConnectionFactory();
            }
            return sessionFactory.openSession();
        } catch (HibernateException e) {
            System.err.print(e);
            destroy();
            return null;
        }
    }

    public static void destroy() {
        timer = 0;
        try {
            if (sessionFactory != null) {
                sessionFactory.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        sessionFactory = null;
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}
